import random
import hashlib
import hmac
import time

import jwt
from django.conf import settings

# 生成随机盐的函数
def generate_salt(length):
    # 可以使用choice来随机选择字符
    salt_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    return ''.join(random.choice(salt_characters) for _ in range(length))


def create_password_hash(password, salt):
    """生成密码哈希"""
    return hmac.new(password.encode('utf-8'), salt.encode('utf-8'), hashlib.sha256).hexdigest()


def crack_token(tokenString):
    # 解密token
    try:
        de_payload_json = jwt.decode(tokenString, settings.MY_TOKEN_CONF['SECRETKEY'], algorithms=['HS256'])
        
        # 判断token是否失效
        now_time = time.time()
        expired_time = de_payload_json['expired']
        if expired_time < now_time:
            return 0
        else:
            return 1
    except Exception as e:
        res_mes = {
            "code": 400,
            "message": "签名验证失败"
        }
        return 0


def get_login_user_id(request, isadmin=False):
    '''
    先判断请求的url里面 有没有携带authorization 头部信息,之后携带了这个信息 才算是正确的，然后再获取缓存session
    '''
    userid = 0
    if isadmin:
        tokenString = request.META.get("HTTP_ADMIN_AUTHORIZATION")
        # 验证token是否过期
        res = crack_token(tokenString)
        if res:
            userid = request.session.get('LOGIN_USER_ID_ADMIN', None)
            # print(userid, "我在这里 admin")
        else:
            return int(0)
    else:
        tokenString = request.META.get("HTTP_AUTHORIZATION")
        # 验证token是否过期
        res = crack_token(tokenString)
        if res:
            userid = request.session.get('LOGIN_USER_ID', None)
            # print(userid, "我在这里 普通")
        else:
            return int(0)


    if userid:
        return userid
    else:
        return int(0)



def rand_num_file(file_ext):
    import random
    rand_num = random.randint(1000000000000000, 9999999999999999)

    rand_file = str(rand_num) + file_ext

    return rand_file

